<?php

function sitemap()
{
global $db;
$select = $db->select();
$select->from('config');
$result = $db->fetchPairs($select);

$sitemap_file = fopen("../sitemap.xml","w") or die ("Ошибка открытия файла");

$sitemap = '<?xml-stylesheet type="text/xsl" href="'.$result['url'].'templates/sitemap.xsl"?>'."\n";
$sitemap .= '<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n";
$select = $db->select();
$select->from(array('con' =>'content'),
              array('url','title','cat_id','date_post','index_page'));
$select->joinLeft(array('cat' => 'category'),
                    'con.cat_id=cat.id',
                    array('caturl'=>'url','name'));
$select->order(array('cat_id','title'));
$count = $db->fetchOne("SELECT COUNT(*) c FROM content ");
$content = $db->fetchAll($select);
$sitemap .= "<url>\n";
$sitemap .= "<loc>\n";
$sitemap .= $result['url']."\n";
$sitemap .= "</loc>\n";
$sitemap .= "<lastmod>\n";
$sitemap .= date('Y-m-d\TH:i:s')."\n";
$sitemap .= "</lastmod>\n";
$sitemap .= "<changefreq>\n daily\n</changefreq>\n<priority>\n 1.0\n</priority>\n</url>\n"; 

for ($i=0;$i<$count;$i++)
{
    if($content[$i]['index_page'] != 1)
    {
	   $sitemap .= "<url>\n";
       $sitemap .= "<loc>\n";
       if($content[$i]['cat_id'] != 1)
       {
            $sitemap .= $result['url'].$content[$i]['caturl']."/".$content[$i]['url'].".html\n";
       }else
       {
            $sitemap .= $result['url'].$content[$i]['url'].".html\n";
       }
       $sitemap .= "</loc>\n";
       $sitemap .= "<lastmod>\n";
       $sitemap .= str_replace(" ","T",$content[$i]['date_post']);
       $sitemap .= "</lastmod>\n";
       $sitemap .= "<changefreq>\n monthly\n</changefreq>\n<priority>\n 0.2\n</priority>\n</url>\n"; 
    }
}
$sitemap .= "</urlset>\n";
fwrite($sitemap_file,$sitemap) or die ("Ошибка записи файла");
fclose($sitemap_file) or die ("Ошибка закрытия файла");
}
?>